package sk.gunna.sms.client;  
      
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import sk.gunna.sms.client.user.UserService;
import sk.gunna.sms.client.user.UserServiceAsync;
import sk.gunna.sms.shared.UserBean;
import sk.gunna.sms.shared.UserType;

import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;  
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabItem;  
import com.extjs.gxt.ui.client.widget.TabPanel;  
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.LabelField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;

      
public class MainTab extends LayoutContainer {
	
	private final UserServiceAsync userService = GWT.create(UserService.class);
	
	private FlexTable stocksFlexTable = new FlexTable();
	private ComboBox<UserType> userTypeCombo = new ComboBox<UserType>();
	TextField<String> emailTextField = new TextField<String>();
	
	private ArrayList<UserBean> users = new ArrayList<UserBean>();
        
	@Override  
	protected void onRender(Element parent, int pos) {  
		super.onRender(parent, pos); 
      
        TabPanel panel = new TabPanel();
        panel.addStyleName("main-tab");
        panel.setPlain(true);  
        panel.setWidth(940);
        panel.setAutoHeight(true);
      
        //sms tab
        TabItem smsTab = new TabItem("SMS");  
        smsTab.addStyleName("pad-text");  
        smsTab.addText("Just a plain old tab");  
        panel.add(smsTab);  
        
        //sms tab
        TabItem templateTab = new TabItem("Templates");  
        templateTab.addStyleName("pad-text");  
        templateTab.addText("templates");  
        panel.add(templateTab);  
      
        //stats tab
        TabItem statisticTab = new TabItem("Statistiky"); 
        statisticTab.addStyleName("pad-text");  
        statisticTab.addText("Tuto budu dajake blbe statistiky.");  
        panel.add(statisticTab);  
        
        
        //admin tab
        TabItem adminTab = new TabItem("Administracia");  
        adminTab .addStyleName("pad-text");
        
        /*
        HorizontalPanel hp = new HorizontalPanel();
        
        LabelField labelNewUser = new LabelField("Novy pouzivatel:");
        labelNewUser.addStyleName("title-label");
        
        emailTextField.addStyleName("test-field");
        emailTextField.setEmptyText("email");
        emailTextField.setWidth(150);
        
       
        ListStore<UserType> userTypes = new ListStore<UserType>();
        userTypes.add(getTypes());
        
        userTypeCombo.setDisplayField("userTypeName");
        userTypeCombo.setStore(userTypes);
        userTypeCombo.setAllowBlank(false);
        userTypeCombo.setEditable(false);
        userTypeCombo.setTriggerAction(TriggerAction.ALL);
        userTypeCombo.setWidth(150);
        hp.add(emailTextField);
        hp.add(userTypeCombo);
        
        
        Button addUserButton = new Button("Pridaj pouzivatela",new SelectionListener<ButtonEvent>() {  
            @Override  
            public void componentSelected(ButtonEvent ce) {  
              addUser();
            }  
          });
        

        
		stocksFlexTable.setText(0, 0, "Email");
		stocksFlexTable.setText(0, 1, "Type");
		stocksFlexTable.setText(0, 2, "Creation Date");
		stocksFlexTable.setText(0, 3, "Last Login");
		stocksFlexTable.setText(0, 4, "Remove");
	
		
		stocksFlexTable.setCellPadding(5);
		stocksFlexTable.getRowFormatter().addStyleName(0, "watchListHeader");
		stocksFlexTable.addStyleName("watchList");
		stocksFlexTable.getCellFormatter().addStyleName(0, 1, "watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(0, 2, "watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(0, 3, "watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(0, 4, "watchListRemoveColumn");
		
		loadUsers();
		
        VerticalPanel vp = new VerticalPanel();
        vp.add(labelNewUser);
        vp.add(hp);
        vp.add(addUserButton);
        vp.add(stocksFlexTable);
        
        adminTab.add(vp);
        */
        adminTab.add(new GridExample());
        panel.add(adminTab);
        

        
        add(panel);  
	} 
      
	private void loadUsers() {
		users.clear();
		userService.getUsers(new AsyncCallback<List<UserBean>>() {
			public void onFailure(Throwable error) {
				//handleError(error);
			}
			public void onSuccess(List<UserBean> users) {
				displayUsers(users);
			}
		});
	}
	
	private void displayUsers(List<UserBean> users) {
		for (UserBean user : users) {
			displayUser(user);
		}
	}
	
	private void displayUser(final UserBean user) {
		
		int row = stocksFlexTable.getRowCount();
		users.add(user);
		stocksFlexTable.setText(row, 0, user.getUserEmail());
		stocksFlexTable.setText(row, 1, user.getUserType());
		stocksFlexTable.setText(row, 2, convertDateToString(user.getCreateDate()));
		stocksFlexTable.setText(row, 3, convertDateToString(user.getLastLogin()));
		/*
		stocksFlexTable.setWidget(row, 2, new Label());
		stocksFlexTable.getCellFormatter().addStyleName(row, 1, "watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(row, 2, "watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(row, 3, "watchListRemoveColumn");
		*/
		
		stocksFlexTable.getCellFormatter().addStyleName(row, 1, "watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(row, 2, "watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(row, 3, "watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(row, 4, "watchListRemoveColumn");
		
		// Add a button to remove this stock from the table.
		Button removeStockButton = new Button("x",new SelectionListener<ButtonEvent>() {  
            @Override  
            public void componentSelected(ButtonEvent ce) {  
            	//removeStock(symbol);
            }  
        });
		
		stocksFlexTable.setWidget(row, 4, removeStockButton);
	}
	

	private List<UserType> getTypes(){
		List<UserType> userType = new ArrayList<UserType>();
		userType.add(new UserType("READER", "Reader"));
		userType.add(new UserType("ADMIN", "Admin"));
		userType.add(new UserType("SUPERADMIN", "SuperAdmin"));
		
		return userType;
	}
	
	/**
	* Add stock to FlexTable. Executed when the user clicks the addStockButton or
	* presses enter in the newSymbolTextBox.
	*/
	private void addUser() {
		String userEmail = emailTextField.getValue();
		UserType userType = userTypeCombo.getValue();
	
		if(userEmail == null || "".equals(userEmail) || userEmail.equals("email")) {
			MessageBox.alert("Chyba", "Zadajte email!", null);
			return;
		}
		
		if(userType == null) {
			MessageBox.alert("Chyba", "Zadajte typ!", null);
			return;
		}
		
		//return if already exist in table
		for(UserBean userBean : users){
			if(userBean.getUserEmail().equals(userEmail)){
				MessageBox.info("Informacia", "Dany email uz je pridany.", null);
				return;
			}
		}
		
		String userTypeName = userType.get("userTypeName");
	    addUser(userEmail, userTypeName);
	}

	private void addUser(final String userEmail, String userType) {
		
		userService.addUser(userEmail, userType, new AsyncCallback<Void>() {
			public void onFailure(Throwable error) {
				//handleError(error);
			}
			public void onSuccess(Void ignore) {
				loadUsers();
			}
		});
	}
	
	private String convertDateToString(Date date){
		if(date == null){
			return "-";
		} else {
			return date.toString();
		}
	}
}  

